﻿using System;
using System.Data;
using System.Data.SqlClient;
using LaRoquita.Model.Entities;

namespace LaRoquita.Model.DAO
{
    public class UserDao
    {
        public User GetUserByEmail(string userMail)
        {
            User user = null;

            using (var sqlConnection = new SqlConnection(@"Data Source=localhost;Database=LaRoquita;Persist Security Info=True;Integrated Security=SSPI;"))
            {
                try
                {
                    var sqlCommand = CreateSqlCommand(sqlConnection, userMail);

                    sqlConnection.Open();

                    var dataReader = sqlCommand.ExecuteReader();

                    while (dataReader.Read())
                    {
                        user = new User
                        {
                            Key = (long)dataReader["Key"],
                            LastName = dataReader["LastName"].ToString(),
                            Mail = dataReader["Mail"].ToString(),
                            Name = dataReader["Name"].ToString()
                        };
                    }
                }
                catch (Exception exeption)
                {
                    throw new Exception(exeption.StackTrace+exeption.Message);
                }
                finally { sqlConnection.Close(); }
            }

            return user;
        }

        private static SqlCommand CreateSqlCommand(SqlConnection sqlConnection, string mail)
        {
            var command = sqlConnection.CreateCommand();

            command.CommandType = CommandType.StoredProcedure;

            command.Parameters.AddWithValue("@Mail", mail);

            command.CommandText = "GetUserByEmail";

            return command;
        }
    }
}